Ext.onReady(function(){
Ext.QuickTips.init();
    
	var login = new Ext.form.FormPanel({ 
        labelWidth:80,
        frame:true, 
        title:'Entre com os dados', 
        defaultType:'textfield',
		//monitorValid:true,
		keys: {
		    key: 13,
		    fn: function(){submit();},
		    scope: this
		},
        listeners:{
    		afterrender: function(cmp){
    				Ext.getCmp('fieldUsuario').focus('',500);
    		}
        },
        items:[{
            xtype: 'label',
			html: '<br/>',
			id: 'labelError'
            },
			{
				fieldLabel:'Usuário', 
            	name:'j_username', 
            	msgTarget: 'side',
            	id: 'fieldUsuario',
            	blankText: 'Este campo é obrigatório!',
            	allowBlank:false,
				width : 166
			},
			{ 
                fieldLabel : 'Senha', 
                name : 'j_password', 
                msgTarget : 'side',
                blankText : 'Este campo é obrigatório!',
                inputType : 'password',
                allowBlank : false,
				width : 166
            }],
 
        buttons:[{ 
                text:'Entrar',
                formBind: true,	 
                handler: function(){submit();} 
        }] 
    });
    
    var win = new Ext.Window({
        layout:'border',
        width:300,
        height:275,
        closable: false,
        resizable: false,
        plain: true,
        border: false,
        items: [{
            xtype: 'panel',
            html: '<center><img src=\'resources/imagens/Sistema_peq.png\' /></center>',
            region: 'north',
            height: 105,
            frame: true
            },{
            layout: 'fit', 
            region: 'center',
            items: [login]
           }
      ]
	});
	win.show();
		
	var submit = function(){ 
	    login.getForm().submit({ 
	        method:'POST', 
	        waitTitle:'Efetuando o login...', 
	        waitMsg:'Efetuando o login...',
			url:'resources/sql/verificaLogin.php',

	        success:function(form, action){
				var redirect;
				var obj = Ext.util.JSON.decode(action.response.responseText);
				var string = obj.errors.reason;
				if(string == 'sala') {
					redirect = 'sala.php';
				}
				if(string == 'equipamento') {
					redirect = 'equipamento.php';
				}
				var label = Ext.getCmp('labelError');
		        label.setText('<span style=\'font-weight:bold;color:blue;text-align:center\'><b>Redirecionando Usuário...</b></span><br/><br/>', false); 
				window.location = redirect;
	        },

			failure:function(form, action){
	            var label = Ext.getCmp('labelError');
	            label.setText('<span style=\'font-weight:bold;color:red;text-align:center\'><b>Usuário inválido. </b></span><br/><br/>', false); 
	            login.getForm().reset(); 
	        } 
	    }); 
	};
});